<script setup>
import { GetAccountSelAPI } from '@/api/common/index.js'

const emit = defineEmits(['update:modelValue', 'clear', 'change'])
const props = defineProps({
  modelValue: {
    type: String || Number,
    default: '',
  },
  option: {
    type: Array,
    default: [],
  },
  // 额外添加
  push: {
    type: Array,
    default: [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  placeholder: {
    type: String,
    default: '请选择收款账户',
  },
  isValue: {
    type: Boolean,
    default: false,
  },
  clearable: {
    type: Boolean,
    default: true,
  },
})

const data = ref('')

watch(
  () => props.modelValue,
  (val) => {
    data.value = val
  },
  { deep: true, immediate: true }
)

watchEffect(() => {
  emit('update:modelValue', data.value)
})

const option = ref([])

// 获取供应商
const initData = async () => {
  const { data: result } = await GetAccountSelAPI()
  if (!Array.isArray(result)) {
    console.error(new Error('p-select组件:option数据类型错误,需要数组类型'))
    option.value = []
  } else {
    option.value = result.map((t) => ({
      label: t.accountName || 'label错误',
      value: t.accountId || 'value错误',
    }))
    if (props.push?.length > 0) {
      option.value = props.push.concat(option.value)
    }
  }
}

initData()

const change = () => {
  emit('change', data.value)
}
</script>

<template>
  <el-select
    filterable
    :disabled="props.disabled"
    :clearable="clearable"
    v-model="data"
    :placeholder="placeholder"
    @clear="emit('clear')"
    @change="change"
  >
    <el-option
      :label="item.label"
      :value="item.value"
      v-for="item in option"
      :key="item.value"
    >
      <span style="float: left">{{ item.label }}</span>
      <span
        v-if="isValue"
        style="
          float: right;
          color: var(--el-text-color-secondary);
          font-size: 13px;
          margin-left: 15px;
        "
        >{{ item.value }}</span
      >
    </el-option>
  </el-select>
</template>
<style scoped lang="scss"></style>
